<template>
  <layout tabbar="/pages/entertainment/index" navbar="none" :showBack="false">
    <view class="entertainment-page">
      <!-- 自定义导航栏 -->
      <tn-nav-bar
        fixed
        alpha
        backgroundColor="#020303"
        :isBack="false"
        fontColor="#FFFFFF">
        <!-- 使用左侧槽位 -->
        <view slot="left" class="nav-left">
          <text class="remaining-text">剩余 {{ remainingCount }} 次</text>
        </view>

          <view class="nav-title">
          美照制作
        </view>

        <!-- 右侧槽位 -->
        <view slot="right" class="nav-right">
        </view>
      </tn-nav-bar>

      <!-- 主要内容区域 -->
      <view class="main-content" :style="{paddingTop: (vuex_status_bar_height || 44) + 44 + 'px'}">

        <!-- 照片对比区域 -->
          <view class="photo-comparison">
          <!-- 左侧上传区域 -->
          <view class="photo-section upload-section">
            <view class="section-header">
              <text class="section-title">原始照片</text>
            </view>
            <view class="photo-container" @tap="selectPhoto">
              <image v-if="originalPhoto" :src="originalPhoto" class="photo" mode="aspectFill" />
              <view v-else class="placeholder">
                <text class="tn-icon-add placeholder-icon"></text>
                <text class="placeholder-text">点击上传</text>
              </view>
              <!-- 上传进度条 -->
              <view class="upload-progress-container" v-if="isUploading">
                <view class="upload-progress-bar" :style="{width: uploadProgress + '%'}"></view>
              </view>
              <!-- 上传中遮罩 -->
              <view class="upload-mask" v-if="isUploading">
                <text class="tn-icon-loading upload-icon rotating"></text>
                <text class="upload-text">上传中 {{ uploadProgress }}%</text>
              </view>
            </view>
              </view>

          <!-- 右侧结果区域 -->
          <view class="photo-section result-section">
            <view class="section-header">
              <text class="section-title">制作结果</text>
              <view class="header-actions">
                <!-- 如果有任务ID但没有结果，显示刷新按钮 -->
<!--                <view v-if="currentTaskId && !generatedPhoto && !isGenerating" class="header-btn" @tap="refreshResult">-->
<!--                  <text class="tn-icon-refresh"></text>-->
<!--                </view>-->
                <!-- 如果有生成结果，显示下载和分享按钮 -->
                <template v-if="generatedPhoto">
                  <view class="header-btn download-btn-animated" @tap="sharePhoto">
                    <text class="tn-icon-download"></text>
                  </view>
<!--                  <view class="header-btn" @tap="sharePhoto">-->
<!--                    <text class="tn-icon-share"></text>-->
<!--                  </view>-->
                </template>
              </view>
            </view>
            <view class="photo-container">
              <image
                v-if="generatedPhoto || previewPhoto"
                :src="generatedPhoto || previewPhoto"
                class="photo"
                :class="{ 'generating': isGenerating && !generatedPhoto, 'clickable': !!generatedPhoto }"
                :style="{
                  filter: isGenerating && !generatedPhoto ? `blur(${blurLevel}px)` : 'none',
                  '-webkit-filter': isGenerating && !generatedPhoto ? `blur(${blurLevel}px)` : 'none'
                }"
                mode="aspectFill"
                @tap="previewImage"
              />
              <view v-else class="placeholder result-placeholder">
                <text v-if="systemBusy" class="tn-icon-warning placeholder-icon error-icon"></text>
                <text v-else class="tn-icon-camera placeholder-icon"></text>
                <text class="placeholder-text" :class="{ 'error-text': systemBusy }">
                  {{ systemBusy ? '系统繁忙，请稍后再试' : (originalPhoto ? '等待制作' : '请先上传照片') }}
                </text>
          </view>
            </view>
          </view>
        </view>

        <!-- 照片类型选择 -->
        <view class="type-selection">
          <view class="type-header">
            <text class="type-title">选择制作类型</text>
          </view>
          <view class="type-options">
              <view
              v-for="type in photoTypes"
              :key="type.id"
              class="type-option"
              :class="{ 'active': selectedType === type.id }"
              @tap="selectType(type.id)"
            >
              <text class="type-icon" :class="type.icon"></text>
              <text class="type-name">{{ type.name }}</text>
              </view>
            </view>
        </view>

        <!-- 生成按钮 -->
        <view class="action-area">
              <view
            class="generate-btn"
            :class="{ 'disabled': !originalPhoto || isGenerating || isUploading || systemBusy }"
            @tap="generatePhoto"
          >
            <text v-if="isGenerating" class="tn-icon-loading btn-icon rotating"></text>
            <text v-else class="tn-icon-camera btn-icon"></text>
            <text class="btn-text">{{ isGenerating ? '制作中...' : '开始制作' }}</text>
                </view>

        </view>

        <!-- 底部空白区域 -->
        <view class="bottom-spacing"></view>

      </view>

      <!-- 生成进度弹窗 -->
      <tn-popup
          mode="center"
          v-model="showProgressModal"
          :maskCloseable="false"
          :customStyle="{borderRadius: '20rpx'}"
          backgroundColor="rgba(0, 0, 0, 0.8)"
      >
        <view class="progress-modal">
          <view class="progress-header">
            <text class="progress-title">正在制作{{ getTypeText(selectedType) }}</text>
          </view>

          <view class="progress-content">
            <!-- 进度条 -->
            <view class="progress-bar-container">
              <view class="progress-bar">
                <view
                    class="progress-fill"
                    :style="{ width: ((currentStep + 1) / generationSteps.length) * 100 + '%' }"
                ></view>
              </view>
              <text class="progress-percentage">{{ Math.round(((currentStep + 1) / generationSteps.length) * 100) }}%</text>
            </view>

            <!-- 当前步骤 -->
            <view class="current-step" v-if="generationSteps[currentStep]">
              <text class="step-icon" :class="generationSteps[currentStep].icon"></text>
              <text class="step-text">{{ generationSteps[currentStep].text }}</text>
            </view>

            <!-- 所有步骤列表 -->
            <view class="steps-list">
              <view
                  v-for="(step, index) in generationSteps"
                  :key="index"
                  class="step-item"
                  :class="{
                'completed': index < currentStep,
                'active': index === currentStep,
                'pending': index > currentStep
              }"
              >
                <view class="step-indicator">
                  <text v-if="index < currentStep" class="tn-icon-check"></text>
                  <text v-else-if="index === currentStep" class="step-number">{{ index + 1 }}</text>
                  <text v-else class="step-number">{{ index + 1 }}</text>
                </view>
                <text class="step-label">{{ step.text }}</text>
              </view>
            </view>
          </view>
        </view>
      </tn-popup>

      <!-- VIP会员开通弹窗 -->
      <vip-popup :show.sync="isVipModalVisible" @purchase-success="onVipPurchaseSuccess"></vip-popup>

      <!-- 自定义分享弹窗 -->
      <share-popup
        :show.sync="isSharePopupVisible"
        :shareImage="generatedPhoto"
        :shareTitle="getShareTitle()"
        :shareDesc="getShareDesc()"
        @share-success="onShareSuccess"
      ></share-popup>

      </view>


  </layout>
</template>

<script>
import Layout from '@/components/layout/layout.vue';
import VipPopup from '@/components/vip/vip-popup.vue';
import SharePopup from '@/components/common/SharePopup.vue';
import { mapState } from 'vuex';
import { uploadFile } from '@/api/upload/index.js';
import { editImage, getMyImage, getRemainingCount } from '@/api/ai/index.js';

export default {
  components: {
    Layout,
    VipPopup,
    SharePopup
  },
  data() {
    return {
      originalPhoto: '', // 原始照片
      generatedPhoto: '', // 生成后的照片
      previewPhoto: '', // 预览照片（用于生成过程中显示）
      isGenerating: false, // 是否正在生成中
      blurLevel: 0, // 模糊程度 0-20
      selectedType: 'id_photo', // 选中的生成类型，默认证件照
      photoTypes: [
        { id: 'id_photo', name: '证件照', icon: 'tn-icon-identity' },
        { id: 'avatar', name: '头像', icon: 'tn-icon-my' },
        { id: 'art_photo', name: '艺术照', icon: 'tn-icon-camera' }
      ],
      currentTaskId: null, // 当前任务ID
      pollingTimer: null, // 轮询定时器
      pollingCount: 0, // 轮询次数
      maxPollingCount: 60, // 最大轮询次数（60次，每2秒一次，总共2分钟）
      clearingTimer: null, // 清晰化动画定时器
      retryCount: 0, // 失败重试次数
      maxRetryCount: 10, // 最大重试次数
      systemBusy: false, // 系统繁忙状态
      // 生成进度相关
      showProgressModal: false, // 是否显示进度弹窗
      currentStep: 0, // 当前步骤索引
      generationSteps: [
        { text: '正在分析照片特征...', icon: 'tn-icon-scan' },
        { text: '启动AI智能处理...', icon: 'tn-icon-cpu' },
        { text: '优化面部细节...', icon: 'tn-icon-brush' },
        { text: '调整光影效果...', icon: 'tn-icon-bulb' },
        { text: '制作最终效果...', icon: 'tn-icon-rocket' }
      ],
      // 图片上传相关
      isUploading: false, // 是否正在上传中
      uploadProgress: 0, // 上传进度

      // 剩余次数
      remainingCount: 0, // 用户剩余生成次数

      // VIP弹窗相关
      isVipModalVisible: false, // 是否显示VIP弹窗

      // 分享弹窗相关
      isSharePopupVisible: false // 是否显示分享弹窗
    };
  },
  computed: {
    // 获取状态栏高度
    ...mapState(['vuex_status_bar_height'])
  },
  methods: {
    // 获取类型文本
    getTypeText(typeId) {
      const type = this.photoTypes.find(item => item.id === typeId);
      return type ? type.name : '';
    },


    // 选择生成类型
    selectType(typeId) {
      this.selectedType = typeId;
      // 清空之前的生成结果，因为类型变了
      if (this.generatedPhoto) {
        this.generatedPhoto = '';
      }
      // 清空预览相关状态
      this.previewPhoto = '';
      this.blurLevel = 0;
      // 清空任务状态
      this.currentTaskId = null;
      this.retryCount = 0; // 重置重试计数器
      this.systemBusy = false; // 重置系统繁忙状态
      this.stopPolling();
      this.stopClearingAnimation(); // 停止清晰化动画
    },

    // 选择照片
    selectPhoto() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'], // 压缩图片
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          // 先显示临时图片
          this.originalPhoto = tempFilePath;
          // 清空之前的生成结果和任务状态
          this.generatedPhoto = '';
          this.currentTaskId = null;
          this.retryCount = 0; // 重置重试计数器
          this.systemBusy = false; // 重置系统繁忙状态
          this.stopPolling();
          this.stopClearingAnimation(); // 停止清晰化动画

          // 开始上传图片到服务器
          this.uploadImage(tempFilePath);
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
        }
      });
    },

    // 上传图片到服务器
    uploadImage(filePath) {
      this.isUploading = true;
      this.uploadProgress = 0;

      uploadFile({
        filePath,
        fileType: 'entertainment', // 娱乐页面相关的图片
        onProgress: (progress) => {
          // 更新上传进度
          this.uploadProgress = progress;
        }
      }).then(result => {
        // 上传成功后，更新URL为服务器返回的URL
        this.originalPhoto = result;
      }).catch(err => {
        // 上传失败处理

        // 清空图片
        this.originalPhoto = '';
        console.error('上传图片失败', err);
      }).finally(() => {
        this.isUploading = false;
        this.uploadProgress = 0;
      });
    },

    // 生成照片
    async generatePhoto() {
      if (!this.originalPhoto || this.isGenerating || this.isUploading || this.systemBusy) {
        return;
      }

      this.isGenerating = true;
      this.currentStep = 0;
      this.currentTaskId = null;
      this.retryCount = 0; // 重置重试计数器
      this.systemBusy = false; // 重置系统繁忙状态

      // 设置预览图片为原图，并添加初始模糊效果
      this.previewPhoto = this.originalPhoto;
      this.blurLevel = 20; // 初始强模糊
      this.generatedPhoto = ''; // 清空之前的生成结果

      try {
        // 调用真实的AI图像编辑接口
        const result = await editImage({
          command: this.selectedType,
          imageUrls: [this.originalPhoto],
          size: '1024x1024',
          quality: 'high',
          isPublic: false
        });

        // 更新任务ID和剩余次数
        this.currentTaskId = result.id;
        this.remainingCount = result.remainingCount;

        console.log(`任务提交成功，ID: ${result.id}，剩余次数: ${result.remainingCount}`);

        // 立即开始查询任务结果（同时执行UI动画）
        this.startQueryingWithAnimation();

      } catch (error) {
        console.error('图像编辑失败:', error);

        // 处理特定的错误信息
        this.handleGenerationError(error);

        this.isGenerating = false;
        this.blurLevel = 0;
        this.previewPhoto = '';
      }
    },

    // 开始查询并同时执行UI动画
    startQueryingWithAnimation() {
      // 初始化查询状态
      this.pollingCount = 0;
      this.currentStep = 0;

      // 开始UI动画
      this.startUIAnimation();

      // 同时开始查询
      this.pollTaskResult();
    },

    // UI动画控制
    startUIAnimation() {
      const stepDuration = 2000; // 与查询间隔一致

      const updateAnimation = () => {
        // 如果还在生成中且没超过最大步骤
        if (this.isGenerating && this.currentStep < this.generationSteps.length - 1) {
          this.currentStep++;

          // 根据查询进度调整模糊度
          const progress = Math.min(this.pollingCount / 10, 1); // 假设10次查询基本能完成
          this.blurLevel = Math.max(2, 20 - (progress * 18)); // 从20逐渐降到2

          setTimeout(updateAnimation, stepDuration);
        }
      };

      updateAnimation();
    },


    // 轮询查询任务结果
    async pollTaskResult() {
      if (this.pollingCount >= this.maxPollingCount) {
        // 达到最大轮询次数，停止轮询和动画
        this.handleQueryTimeout();
        return;
      }

      try {
        this.pollingCount++;
        console.log(`第${this.pollingCount}次查询任务结果，任务ID: ${this.currentTaskId}`);

        // 实时更新模糊效果（基于查询进度）
        const progress = Math.min(this.pollingCount / 15, 0.9); // 15次查询达到90%进度
        this.blurLevel = Math.max(1, 20 - (progress * 19)); // 从20逐渐降到1

        // 调用查询接口
        const result = await getMyImage(this.currentTaskId);

        if (result) {
          // 检查任务状态
          if (result.status === 20) {
            // 任务已完成
            this.handleTaskComplete(result);
          } else if (result.status === 30) {
            // 任务失败
            this.handleTaskFailed(result);
          } else if (result.status === 10) {
            // 任务进行中，继续轮询
            console.log('任务进行中，2秒后重新查询...');
            this.pollingTimer = setTimeout(() => {
              this.pollTaskResult();
            }, 2000);
          } else {
            // 未知状态，继续轮询
            console.log('未知任务状态:', result.status);
            this.pollingTimer = setTimeout(() => {
              this.pollTaskResult();
            }, 2000);
          }
        } else {
          // 查询结果为空，继续轮询
          console.log('查询结果为空，2秒后重新查询...');
          this.pollingTimer = setTimeout(() => {
            this.pollTaskResult();
          }, 2000);
        }
      } catch (error) {
        console.error('查询任务结果失败:', error);

        // 查询失败，继续轮询（可能是网络问题）
        if (this.pollingCount < this.maxPollingCount) {
          console.log('查询失败，2秒后重试...');
          this.pollingTimer = setTimeout(() => {
            this.pollTaskResult();
          }, 2000);
        } else {
          this.handleQueryTimeout();
        }
      }
    },

    // 处理任务完成
    handleTaskComplete(result) {
      this.stopPolling();

      console.log('任务完成，结果:', result);

      // 检查是否有生成的图片URL
      if (result.picUrl) {
        // 先将结果图片替换到预览区域（保持模糊状态）
        this.previewPhoto = result.picUrl;

        // 然后慢慢让图片变清晰
        this.startClearingAnimation(result.picUrl);
      } else {
        // 没有图片URL，直接停止所有效果
        this.stopGenerating();
        this.generatedPhoto = this.originalPhoto; // 显示原图
      }
    },

    // 处理任务失败
    handleTaskFailed(result) {
      this.stopPolling();

      console.log('任务失败，原因:', result.errorMessage || '未知错误');
      console.log(`当前重试次数: ${this.retryCount}/${this.maxRetryCount}`);

      // 检查是否还能重试
      if (this.retryCount < this.maxRetryCount) {
        this.retryCount++;
        console.log(`开始第${this.retryCount}次重试...`);

        // 重新提交任务
        this.retrySubmitTask();
      } else {
        // 超过最大重试次数，彻底失败
        this.handleFinalFailure();
      }
    },

    // 处理生成错误
    handleGenerationError(error) {
      console.log('处理生成错误:', error);

      // 按照项目标准处理错误码
      if (error.code === 1040009000) {
        // 免费次数已用完，需要开通VIP
        uni.showModal({
          title: '会员特权',
          content: error.msg || '您免费图片生成次数已用完，开通VIP会员可享更多次数',
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              // 显示VIP弹窗或跳转到VIP页面
              this.isVipModalVisible = true;
            }
          }
        });
        return;
      } else if (error.code === 1040009001) {
        // 今日次数已用完
        uni.showModal({
          title: '今日次数已用完',
          content: error.msg || '您今日图片生成次数已用完，明天再来吧',
          showCancel: false,
          confirmText: '我知道了'
        });
        this.remainingCount = 0;
        return;
      }

      // 其他错误统一显示toast
      uni.showToast({
        title: error.msg || '生成失败，请稍后重试',
        icon: 'none',
        duration: 3000
      });
    },

    // 重新提交任务（失败重试）
    async retrySubmitTask() {
      try {
        console.log('重新提交任务...');

        // 重新设置预览状态（不重置生成状态，保持isGenerating=true）
        this.previewPhoto = this.originalPhoto;
        this.blurLevel = 20;
        this.currentTaskId = null;
        this.pollingCount = 0;

        // 调用AI图像编辑接口
        const result = await editImage({
          command: this.selectedType,
          imageUrls: [this.originalPhoto],
          size: '1024x1024',
          quality: 'high',
          isPublic: false
        });

        // 更新任务ID和剩余次数
        this.currentTaskId = result.id;
        this.remainingCount = result.remainingCount;

        console.log(`重试任务提交成功，新任务ID: ${result.id}，剩余次数: ${result.remainingCount}`);

        // 立即开始查询
        this.startQueryingWithAnimation();

      } catch (error) {
        console.error('重试提交失败:', error);

        // 处理重试时的错误
        this.handleGenerationError(error);

        // 重试提交失败，也算一次重试，继续检查是否还能重试
        if (this.retryCount < this.maxRetryCount) {
          this.retryCount++;
          console.log(`提交失败，继续第${this.retryCount}次重试...`);

          // 延迟1秒后再重试
          setTimeout(() => {
            this.retrySubmitTask();
          }, 1000);
        } else {
          // 彻底失败
          this.handleFinalFailure();
        }
      }
    },

    // 处理最终失败（超过重试次数）
    handleFinalFailure() {
      this.stopGenerating(); // 停止所有动画和生成状态

      console.log('任务彻底失败，已达最大重试次数');
      console.log('系统繁忙，请稍后再试');

      // 清空生成结果
      this.generatedPhoto = '';

      // 设置系统繁忙状态，显示提示信息
      this.systemBusy = true;
    },

    // 处理查询超时
    handleQueryTimeout() {
      this.stopPolling();

      // 查询超时也视为失败，进入重试逻辑
      console.log('查询超时，视为任务失败');
      this.handleTaskFailed({ errorMessage: '查询超时' });
    },

    // 停止生成状态和动画
    stopGenerating() {
      this.isGenerating = false;
      this.blurLevel = 0;
      this.previewPhoto = '';
      this.currentStep = 0;
      this.stopClearingAnimation(); // 也要停止清晰化动画
    },

    // 开始清晰化动画（查询到结果后）
    startClearingAnimation(resultImageUrl) {
      // 清除之前的清晰化动画
      this.stopClearingAnimation();

      // 停止生成状态，但保持预览图片
      this.isGenerating = false;
      this.currentStep = 0;

      // 开始清晰化过程
      const clearingDuration = 1500; // 1.5秒清晰化过程
      const steps = 15; // 15个步骤
      const stepDuration = clearingDuration / steps;
      const currentBlur = this.blurLevel; // 保存当前模糊度
      let currentStep = 0;

      this.clearingTimer = setInterval(() => {
        currentStep++;
        const progress = currentStep / steps;

        // 从当前模糊度逐渐降到0
        this.blurLevel = Math.max(0, currentBlur * (1 - progress));

        if (currentStep >= steps) {
          // 清晰化完成
          this.stopClearingAnimation();
          this.blurLevel = 0;

          // 将结果设置为最终生成图片，清空预览
          this.generatedPhoto = resultImageUrl;
          this.previewPhoto = '';

          console.log('清晰化动画完成');
        }
      }, stepDuration);
    },

    // 停止清晰化动画
    stopClearingAnimation() {
      if (this.clearingTimer) {
        clearInterval(this.clearingTimer);
        this.clearingTimer = null;
      }
    },

    // 停止轮询
    stopPolling() {
      if (this.pollingTimer) {
        clearTimeout(this.pollingTimer);
        this.pollingTimer = null;
      }
      this.pollingCount = 0;
    },

    // 手动刷新结果
    refreshResult() {
      if (!this.currentTaskId) {
        return;
      }

      // 停止当前的查询
      if (this.pollingTimer) {
        this.stopPolling();
      }

      // 重新设置UI状态（不影响生成状态，只是重新开始查询）
      this.previewPhoto = this.originalPhoto;
      this.blurLevel = 15; // 从中等模糊开始

      // 重新开始查询
      this.pollingCount = 0;
      this.pollTaskResult();
    },

    // 下载照片
    downloadPhoto() {
      if (!this.generatedPhoto) {
        return;
      }

      uni.downloadFile({
        url: this.generatedPhoto,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                // 保存成功
              },
              fail: () => {
                // 保存失败
              }
            });
          }
        },
        fail: () => {
          // 下载失败
        }
      });
    },

    // 预览图片
    previewImage() {
      if (!this.generatedPhoto) {
        return;
      }

      uni.previewImage({
        urls: [this.generatedPhoto], // 预览的图片链接列表
        current: this.generatedPhoto, // 当前显示图片的链接
        longPressActions: {
          itemList: ['发送给朋友', '保存图片', '收藏'],
          success: (data) => {
            if (data.tapIndex == 0) {
              // 发送给朋友
              console.log('发送给朋友');
            } else if (data.tapIndex == 1) {
              // 保存图片
              this.downloadPhoto();
            } else if (data.tapIndex == 2) {
              // 收藏
              console.log('收藏图片');
            }
          },
          fail: (err) => {
            console.log('长按操作失败:', err);
          }
        }
      });
    },

    // 分享照片
    sharePhoto() {
      if (!this.generatedPhoto) {
        return;
      }

      // 显示自定义分享弹窗
      this.isSharePopupVisible = true;
    },

    // 分享成功回调
    onShareSuccess(shareInfo) {
      console.log('分享成功:', shareInfo);

      // 可以在这里添加分享成功的统计或其他逻辑
      uni.showToast({
        title: `已${shareInfo.platform === '微信好友' ? '分享到' : ''}${shareInfo.platform}`,
        icon: shareInfo.type === 'save' ? 'success' : 'none',
        duration: 2000
      });
    },

    // VIP购买成功回调
    onVipPurchaseSuccess(purchaseInfo) {
      console.log('VIP购买成功', purchaseInfo);

      // 购买成功后重新获取剩余次数
      this.getRemainingCount();

      uni.showToast({
        title: 'VIP开通成功！',
        icon: 'success',
        duration: 2000
      });
    },

    // 获取剩余次数
    async getRemainingCount() {
      try {
        const count = await getRemainingCount();
        this.remainingCount = count;
        console.log('获取剩余次数成功:', count);
      } catch (error) {
        console.error('获取剩余次数失败:', error);
        // 如果获取失败，不显示剩余次数
        this.remainingCount = null;
      }
    },

    // 获取分享标题
    getShareTitle() {
      const typeText = this.getTypeText(this.selectedType);
      return `我的AI${typeText}制作完成！`;
    },

    // 获取分享描述
    getShareDesc() {
      const typeText = this.getTypeText(this.selectedType);
      return `快来看看我用AI制作的${typeText}，效果超棒的！`;
    }
  },
  onLoad() {
    // 页面加载时获取剩余次数
    this.getRemainingCount();
  },
  onHide() {
    // 页面隐藏时停止所有定时器
    // this.stopPolling();
    // this.stopClearingAnimation();
  },
  onUnload() {
    // 页面卸载时停止所有定时器
    this.stopPolling();
    this.stopClearingAnimation();
  },

  // #ifdef MP-WEIXIN
  // 微信小程序分享
  onShareAppMessage() {
    const shareTitle = this.getShareTitle();
    const shareDesc = this.getShareDesc();

    // 如果有生成的图片，使用生成的图片作为分享图，否则使用微信图标
    const shareImageUrl = this.generatedPhoto || '/static/images/wechat.png';

    console.log('微信分享配置:', {
      title: shareTitle,
      desc: shareDesc,
      imageUrl: shareImageUrl
    });

    return {
      title: shareTitle,
      desc: shareDesc,
      imageUrl: shareImageUrl,
      path: `/pages/entertainment/index?shared=1&type=${this.selectedType}`,
      success: (res) => {
        console.log('分享成功', res);
        uni.showToast({
          title: '分享成功',
          icon: 'success'
        });
      },
      fail: (err) => {
        console.log('分享失败', err);
        uni.showToast({
          title: '分享失败',
          icon: 'none'
        });
      }
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    const shareTitle = this.getShareTitle();
    const shareImageUrl = this.generatedPhoto || '/static/images/wechat.png';

    console.log('朋友圈分享配置:', {
      title: shareTitle,
      imageUrl: shareImageUrl
    });

    return {
      title: shareTitle,
      imageUrl: shareImageUrl,
      path: `/pages/entertainment/index?shared=1&type=${this.selectedType}`,
      success: (res) => {
        console.log('分享到朋友圈成功', res);
        uni.showToast({
          title: '分享成功',
          icon: 'success'
        });
      },
      fail: (err) => {
        console.log('分享到朋友圈失败', err);
        uni.showToast({
          title: '分享失败',
          icon: 'none'
        });
      }
    };
  }
  // #endif
};
</script>

<style lang="scss" scoped>
.entertainment-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #020303 0%, #0a0a0a 100%);
  color: #e0e0e0;

    .nav-title {
      font-size: 36rpx;
      font-weight: 700;
      color: #e0e0e0;
      position: relative;
      text-align: center;
      height: 70rpx;

      &::after {
        content: '';
        position: absolute;
        bottom: -10rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 4rpx;
        background: linear-gradient(90deg, #8eac21, #B3F73C);
        border-radius: 2rpx;
      }
    }

  .nav-left {
        display: flex;
        align-items: center;
    margin-left: 30rpx;

    .remaining-text {
      font-size: 24rpx;
      color: #B3F73C;
      background: rgba(179, 247, 60, 0.1);
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      border: 1px solid rgba(179, 247, 60, 0.3);
      font-weight: 600;
    }
  }

  // 主要内容区域
  .main-content {
    padding: 30rpx;
    height: calc(100vh - 88px - 60px); // 固定导航栏高度88px + 额外60px空间
    min-height: 500rpx; // 最小高度保证
    display: flex;
    flex-direction: column;
  }

  // 照片对比区域
    .photo-comparison {
    display: flex;
      gap: 20rpx;
    flex: 1;
    margin-bottom: 20rpx;

    .photo-section {
      flex: 1;
      background: rgba(255, 255, 255, 0.05);
      border-radius: 15rpx;
      border: 1px solid rgba(255, 255, 255, 0.1);
      overflow: hidden;
        display: flex;
        flex-direction: column;

      .section-header {
        padding: 20rpx 25rpx;
        border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        display: flex;
        justify-content: space-between;
        align-items: center;
        min-height: 80rpx; // 固定最小高度，防止按钮出现时变高

        .section-title {
          font-size: 28rpx;
          font-weight: 600;
          color: #e0e0e0;
        }

        .header-actions {
          display: flex;
          gap: 15rpx;
          align-items: center; // 确保按钮垂直居中
          flex-shrink: 0; // 防止按钮被压缩

          .header-btn {
            width: 50rpx;
            height: 50rpx;
            background: rgba(179, 247, 60, 0.1);
            border-radius: 50%;
      display: flex;
    align-items: center;
    justify-content: center;
        border: 1px solid rgba(179, 247, 60, 0.2);

            text {
        font-size: 24rpx;
        color: #B3F73C;
        }

        &:active {
              background: rgba(179, 247, 60, 0.2);
            }
          }

          // 下载按钮动画效果
          .download-btn-animated {
            position: relative;
            animation: downloadPulse 2s infinite;
            
            &::before {
              content: '';
              position: absolute;
              top: -2rpx;
              left: -2rpx;
              right: -2rpx;
              bottom: -2rpx;
              border-radius: 50%;
              background: linear-gradient(45deg, #B3F73C, #8FD429);
              opacity: 0;
              z-index: -1;
              animation: downloadGlow 2s infinite;
            }

            &:hover {
              animation: downloadPulse 1s infinite;
            }
          }

          @keyframes downloadPulse {
            0%, 100% {
              transform: scale(1);
              box-shadow: 0 0 0 0 rgba(179, 247, 60, 0.4);
            }
            50% {
              transform: scale(1.05);
              box-shadow: 0 0 0 8rpx rgba(179, 247, 60, 0.1);
            }
          }

          @keyframes downloadGlow {
            0%, 100% {
              opacity: 0;
              transform: scale(1);
            }
            50% {
              opacity: 0.3;
              transform: scale(1.2);
            }
          }
        }
      }

      .photo-container {
        flex: 1;
        padding: 20rpx;
        position: relative;
        min-height: 400rpx;
        height: 400rpx; // 保持固定高度，不受header变化影响
        display: flex;
        align-items: center;
        justify-content: center;

        .photo {
          width: 100%;
          height: 100%;
          max-width: 100%;
          max-height: 100%;
          border-radius: 12rpx;
          object-fit: cover;
          display: block; // 确保图片正常显示
          transition: filter 0.5s ease; // 模糊效果平滑过渡

          &.generating {
            // 生成中的特殊样式
          }

          &.clickable {
            cursor: pointer;

            &:hover {
              transform: scale(1.02);
              transition: all 0.2s ease;
            }

            &:active {
              transform: scale(0.98);
            }
          }
        }

        .placeholder {
          width: 100%;
          height: 100%;
          min-height: 250rpx;
          border: 2rpx dashed rgba(179, 247, 60, 0.3);
          border-radius: 12rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
          background: rgba(179, 247, 60, 0.05);
          transition: all 0.2s ease;

          .placeholder-icon {
            font-size: 50rpx;
            color: rgba(179, 247, 60, 0.7);
            margin-bottom: 15rpx;
          }

          .placeholder-text {
            font-size: 26rpx;
            color: rgba(179, 247, 60, 0.8);
        }

        &:active {
            background: rgba(179, 247, 60, 0.1);
            border-color: rgba(179, 247, 60, 0.5);
            transform: scale(0.98);
          }
        }

        // 上传进度条
        .upload-progress-container {
          position: absolute;
          bottom: 20rpx;
          left: 20rpx;
          right: 20rpx;
          height: 6rpx;
          background-color: rgba(255, 255, 255, 0.3);
          border-radius: 3rpx;
          overflow: hidden;
          z-index: 30;
        }

        .upload-progress-bar {
          height: 100%;
          background: linear-gradient(90deg, #B3F73C, #8FD429);
          width: 0%;
          transition: width 0.3s ease;
          border-radius: 2rpx;
        }

        // 上传中遮罩
        .upload-mask {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.75);
          border-radius: 15rpx;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          backdrop-filter: blur(2rpx);

          .upload-icon {
            font-size: 48rpx;
            color: #B3F73C;
            margin-bottom: 20rpx;
            animation: spin 1s linear infinite;
          }

          .upload-text {
            font-size: 28rpx;
            color: #FFFFFF;
            font-weight: 500;
          }
        }

        @keyframes spin {
          from {
            transform: rotate(0deg);
          }
          to {
            transform: rotate(360deg);
          }
        }

        .result-placeholder {
          border-color: rgba(255, 255, 255, 0.2);
          background: rgba(255, 255, 255, 0.02);

          .placeholder-icon {
            color: rgba(255, 255, 255, 0.4);

            &.error-icon {
              color: #ff6b6b; // 错误状态为红色
            }
          }

          .placeholder-text {
            color: rgba(255, 255, 255, 0.5);
            text-align: center;
            line-height: 1.4;

            &.error-text {
              color: #ff6b6b; // 错误文本为红色
              font-weight: 500;
            }
        }

        &:active {
            transform: none; // 结果区域不需要点击效果
          }
        }
      }
    }
  }

  // 照片类型选择区域
  .type-selection {
    margin-bottom: 20rpx;

    .type-header {
      margin-bottom: 15rpx;
      text-align: center;

      .type-title {
        font-size: 26rpx;
        color: rgba(224, 224, 224, 0.8);
        font-weight: 500;
      }
    }

    .type-options {
      display: flex;
            justify-content: center;
      gap: 15rpx;

      .type-option {
        flex: 1;
        max-width: 120rpx;
        padding: 20rpx 15rpx;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 12rpx;
        border: 1px solid rgba(255, 255, 255, 0.1);
          display: flex;
        flex-direction: column;
            align-items: center;
        gap: 8rpx;
        transition: all 0.2s ease;

        .type-icon {
          font-size: 28rpx;
          color: rgba(224, 224, 224, 0.6);
          transition: all 0.2s ease;
        }

        .type-name {
            font-size: 22rpx;
          color: rgba(224, 224, 224, 0.7);
          transition: all 0.2s ease;
          text-align: center;
        }

            &:active {
          transform: scale(0.95);
        }

        &.active {
          background: rgba(179, 247, 60, 0.1);
          border-color: rgba(179, 247, 60, 0.3);

          .type-icon {
            color: #B3F73C;
            transform: scale(1.1);
          }

          .type-name {
            color: #B3F73C;
            font-weight: 600;
          }
        }

        &:not(.active):hover {
          background: rgba(255, 255, 255, 0.08);
          border-color: rgba(255, 255, 255, 0.15);

          .type-icon {
          color: rgba(224, 224, 224, 0.8);
          }

          .type-name {
            color: rgba(224, 224, 224, 0.9);
          }
        }
      }
    }
  }

  // 操作区域
  .action-area {
    display: flex;
    justify-content: center;
    padding: 40rpx 30rpx 30rpx;

    .generate-btn {
      width: 500rpx;
      height: 88rpx;
      background: linear-gradient(135deg, #B3F73C 0%, #9EE32A 100%);
      border-radius: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 16rpx;
      color: #1A1A1A;
      font-weight: 700;
      font-size: 32rpx;
      transition: all 0.3s ease;
      box-shadow: 0 8rpx 24rpx rgba(179, 247, 60, 0.25), 0 2rpx 8rpx rgba(179, 247, 60, 0.15);
      position: relative;
      overflow: hidden;

      // 按钮内光效
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
        transition: left 0.5s ease;
      }

      &:active::before {
        left: 100%;
      }

      &:hover {
        transform: translateY(-2rpx);
        box-shadow: 0 12rpx 32rpx rgba(179, 247, 60, 0.3), 0 4rpx 12rpx rgba(179, 247, 60, 0.2);
      }

      &:active {
        background: linear-gradient(135deg, #9EE32A 0%, #8BD018 100%);
        transform: translateY(0rpx) scale(0.98);
        box-shadow: 0 4rpx 16rpx rgba(179, 247, 60, 0.3);
      }

      &.disabled {
        background: rgba(255, 255, 255, 0.08);
        color: rgba(255, 255, 255, 0.3);
        box-shadow: none;
        cursor: not-allowed;

        &::before {
          display: none;
        }

        .btn-icon, .btn-text {
          opacity: 0.4;
        }

        &:hover, &:active {
          transform: none;
          box-shadow: none;
        }
      }

      .btn-icon {
        font-size: 32rpx;
        z-index: 1;

        &.rotating {
          animation: rotate 1.2s linear infinite;
        }
      }

      .btn-text {
        white-space: nowrap;
        z-index: 1;
        letter-spacing: 1rpx;
      }
    }
  }

  // 底部空白区域
  .bottom-spacing {
    height: 40rpx;
  }

  // 简单旋转动画
  @keyframes rotate {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }

  // 响应式设计 - 小屏幕适配
  @media screen and (max-width: 400px) {
    .main-content {
      padding: 20rpx;
    }

    .photo-comparison {
      gap: 15rpx;

      .photo-section {
        .section-header {
          padding: 15rpx 20rpx;

          .section-title {
            font-size: 26rpx;
          }

          .header-actions .header-btn {
            width: 45rpx;
            height: 45rpx;

            text {
              font-size: 22rpx;
            }
          }
        }

        .photo-container {
          padding: 15rpx;
          min-height: 250rpx;

          .placeholder {
            min-height: 200rpx;

            .placeholder-icon {
              font-size: 45rpx;
            }

            .placeholder-text {
              font-size: 24rpx;
            }
          }
        }
      }
    }

    .type-selection {
      margin-bottom: 15rpx;

      .type-header .type-title {
        font-size: 24rpx;
      }

      .type-options {
        gap: 10rpx;

        .type-option {
          max-width: 100rpx;
          padding: 15rpx 10rpx;

          .type-icon {
            font-size: 26rpx;
          }

          .type-name {
              font-size: 20rpx;
          }
        }
      }
    }

    .action-area {
      padding: 30rpx 20rpx 25rpx;

      .generate-btn {
        width: 420rpx;
        height: 78rpx;
        font-size: 28rpx;

        .btn-icon {
          font-size: 28rpx;
        }

        .btn-text {
          letter-spacing: 0.5rpx;
        }
      }
    }
  }

  // 进度弹窗样式

  .progress-modal {
    width: 550rpx;
    background: linear-gradient(145deg, #1a1a1a, #2d2d2d);
    border-radius: 20rpx;
    border: 1px solid rgba(179, 247, 60, 0.2);
    box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.3);
    overflow: hidden;
    animation: modalSlideIn 0.3s ease-out;
  }

  @keyframes modalSlideIn {
    from {
      transform: scale(0.8) translateY(50rpx);
      opacity: 0;
    }
    to {
      transform: scale(1) translateY(0);
      opacity: 1;
    }
  }

  .progress-header {
    padding: 30rpx 40rpx 20rpx;
    text-align: center;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    .progress-title {
      font-size: 32rpx;
      color: #B3F73C;
      font-weight: 600;
    }
  }

  .progress-content {
    padding: 30rpx 40rpx 40rpx;
  }

  .progress-bar-container {
    margin-bottom: 30rpx;

    .progress-bar {
      height: 8rpx;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 4rpx;
      overflow: hidden;
      margin-bottom: 10rpx;

      .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #B3F73C, #8FD429);
        border-radius: 4rpx;
        transition: width 0.5s ease;
        animation: progressGlow 2s infinite;
      }
    }

    .progress-percentage {
      font-size: 24rpx;
      color: rgba(224, 224, 224, 0.8);
      text-align: center;
      display: block;
    }
  }

  @keyframes progressGlow {
    0%, 100% {
      box-shadow: 0 0 8rpx rgba(179, 247, 60, 0.3);
    }
    50% {
      box-shadow: 0 0 16rpx rgba(179, 247, 60, 0.6);
    }
  }

  .current-step {
    display: flex;
    align-items: center;
    gap: 15rpx;
    margin-bottom: 30rpx;
    padding: 20rpx;
    background: rgba(179, 247, 60, 0.05);
    border-radius: 12rpx;
    border: 1px solid rgba(179, 247, 60, 0.2);

    .step-icon {
      font-size: 28rpx;
        color: #B3F73C;
      animation: iconPulse 1.5s infinite;
    }

    .step-text {
      font-size: 26rpx;
      color: rgba(224, 224, 224, 0.9);
        flex: 1;
    }
  }

  @keyframes iconPulse {
    0%, 100% {
      transform: scale(1);
      opacity: 1;
    }
    50% {
      transform: scale(1.1);
      opacity: 0.8;
    }
  }

  .steps-list {
    .step-item {
        display: flex;
        align-items: center;
      gap: 20rpx;
      padding: 15rpx 0;
      border-bottom: 1px solid rgba(255, 255, 255, 0.05);

      &:last-child {
        border-bottom: none;
      }

      .step-indicator {
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20rpx;
        font-weight: 600;
        flex-shrink: 0;
        transition: all 0.3s ease;

        .step-number {
          font-size: 20rpx;
        }
      }

      .step-label {
        font-size: 24rpx;
        transition: all 0.3s ease;
      }

      // 已完成状态
      &.completed {
        .step-indicator {
          background: #B3F73C;
          color: #000;

          .tn-icon-check {
            color: #000;
            font-weight: bold;
          }
        }

        .step-label {
          color: rgba(224, 224, 224, 0.7);
          text-decoration: line-through;
        }
      }

      // 当前进行状态
      &.active {
        .step-indicator {
          background: linear-gradient(45deg, #B3F73C, #8FD429);
          color: #000;
          animation: activeStepPulse 2s infinite;
        }

        .step-label {
        color: #B3F73C;
          font-weight: 500;
        }
      }

      // 待执行状态
      &.pending {
        .step-indicator {
          background: rgba(255, 255, 255, 0.1);
          color: rgba(224, 224, 224, 0.5);
          border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .step-label {
          color: rgba(224, 224, 224, 0.5);
        }
      }
    }
  }

  @keyframes activeStepPulse {
    0%, 100% {
      transform: scale(1);
      box-shadow: 0 0 0 0 rgba(179, 247, 60, 0.7);
    }
    50% {
      transform: scale(1.05);
      box-shadow: 0 0 0 8rpx rgba(179, 247, 60, 0.2);
    }
  }
}
</style>
